package iinflux

import (
	"context"
	"fmt"
	"gitee.com/tietang/terrace-go/v2/base"
	influxdb2 "github.com/influxdata/influxdb-client-go"
	"github.com/influxdata/influxdb-client-go/api"
	"github.com/influxdata/influxdb-client-go/domain"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/props/v3/kvs"
	"time"
)

const (
	timeout = 10 * time.Second
)

var influxDbClient influxdb2.Client
var org string
var orgId string
var bucketName string
var bucket *domain.Bucket

func Bucket() *domain.Bucket {
	return bucket
}

func BucketName() string {
	return bucketName
}
func WriteAPI() api.WriteAPI {
	return influxDbClient.WriteAPI(org, bucket.Name)
}
func WriteAPIBlocking() api.WriteAPIBlocking {
	return influxDbClient.WriteAPIBlocking(org, bucket.Name)
}

func QueryAPI() api.QueryAPI {
	return influxDbClient.QueryAPI(org)
}

func InfluxDbClient() influxdb2.Client {
	base.Check(influxDbClient)
	return influxDbClient
}

func Ctx() context.Context {
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	return ctx
}

type InfluxStarter struct {
	base.BaseStarter
	url        string
	authToken  string
	org        string
	bucketName string
	bucket     *domain.Bucket
	options    *influxdb2.Options
	client     influxdb2.Client
}

const (
	URL = "http://%s"
)

func (s *InfluxStarter) Init(ctx base.StarterContext) {
	conf := ctx.Props()
	host := conf.GetDefault("influxDb.host", "172.16.1.248")

	s.url = fmt.Sprintf(URL, host)
	s.authToken = conf.GetDefault("influxDb.authToken", "")
	s.org = conf.GetDefault("influxDb.org", "")
	org = s.org
	s.bucketName = conf.GetDefault("influxDb.bucketName", "")
	bucketName = s.bucketName
	s.options = influxdb2.DefaultOptions()
	err := kvs.Unmarshal(conf, s.options, "influxDb")
	if err != nil {
		log.Error(err)
	}
	log.Infof("influxDb options: %+v\n", s.options)

}

func (s *InfluxStarter) Start(ctx base.StarterContext) {
	s.client = influxdb2.NewClientWithOptions(s.url, s.authToken, s.options)
	influxDbClient = s.client
	s.createBucket(ctx)

}
func (s *InfluxStarter) createBucket(ctx base.StarterContext) {
	bucketReq := domain.Bucket{
		Name:           s.bucketName,
		OrgID:          &s.org,
		RetentionRules: domain.RetentionRules{},
	}
	b, err := s.client.BucketsAPI().FindBucketByName(context.Background(), s.bucketName)
	if err != nil {
		log.Error(err)
	}
	if b == nil {
		s.bucket, err = s.client.BucketsAPI().CreateBucket(context.Background(), &bucketReq)
		if err != nil {
			log.Error(err)
		}
	}
	s.bucket = b
	bucket = b
}

func (s *InfluxStarter) Stop(ctx base.StarterContext) {
	s.client.Close()
}
